package com.vfa.vocaburay;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.vfa.data.Question;
import com.vfa.file.FileAdapter;
import com.vfa.file.FileInfo;
import com.vfa.file.ListArrayAdapter;
import com.vfa.test.QuestionData;

public class ImportQuestion extends Activity {
	 public static final int DIALOG_IMPORT_PROGRESS = 0;
	 private ProgressBar mProgressbarImportFile;
	 private TextView mTVStatus;
	 private ListView mListFile;
	 private TextView mTVPath;
	 private FileAdapter mFileAdapter;
	 private String  defaultPath = "/android/data/com.vfa.vocabulary";
	 private ListArrayAdapter mAdapter;
	 QuestionData questiondata;
	 private boolean isImporting = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.importfilescv);
		//
		questiondata = new QuestionData(this);
		Button btImport = (Button) findViewById(R.id.btImport);
		Button btBrowser = (Button) findViewById(R.id.btBrowser);
		mTVPath = (TextView) findViewById(R.id.tvPath);
		//progressbar
		mProgressbarImportFile = (ProgressBar) findViewById(R.id.progressBarImportFile);
		mProgressbarImportFile.setProgress(0);
		mProgressbarImportFile.setVisibility(View.INVISIBLE);
		mTVStatus = (TextView) findViewById(R.id.tvStatusImport);
		mTVStatus.setText(" ");
		mTVStatus.setVisibility(View.INVISIBLE);
		mListFile = (ListView) findViewById(R.id.listViewFile);
		//mListFile.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice, listFiles));
		//choose single mode
		mListFile.setChoiceMode(1);
		mListFile.setTextFilterEnabled(true);
		mFileAdapter = new FileAdapter(".xml");
		//check default path
		defaultPath = Environment.getExternalStorageDirectory()+ defaultPath;
		File file = new File(defaultPath);
		if(!file.exists() || !file.isDirectory())
		{
			if(!file.mkdir())
			{
				Toast.makeText(getBaseContext(), "can't make default path in sdcard!", Toast.LENGTH_SHORT).show();
				return;
			}
			
		}
		
		mFileAdapter.getDir(defaultPath,1,false,false);
		mTVPath.setText(defaultPath);
		this.mAdapter = new ListArrayAdapter(this,R.layout.item_choose_single_file,
				mFileAdapter.getFileInfos());
		
		System.out.println(mAdapter.getCount());
		mListFile.setAdapter(mAdapter);
		mListFile.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				ListView temp = (ListView)arg0;
				temp.setItemChecked(arg2, temp.isItemChecked((int)arg3));
			}
			
		});
		btImport.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//mdialog.showDialog();
				if(isImporting == true)
				{
					Log.d("KitVS", "App is importing words");
					return;
				}
				int itemcheck = mListFile.getCheckedItemPosition();
				if(itemcheck != -1)
				{
					mProgressbarImportFile.setVisibility(View.VISIBLE);
					mTVStatus.setVisibility(View.VISIBLE);
					FileInfo filenameChoose = (FileInfo)mListFile.getItemAtPosition(itemcheck);
					new DoBackgroundImportFile().execute(filenameChoose.mFilePath);
				}
				else
				{
					Toast.makeText(getBaseContext(), "Please choose  a  file to import!", Toast.LENGTH_SHORT).show();
				}

			}
		});
		btBrowser.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//dung activity file ex nhan dc dc folder co chua file csv;
				//.....
				//gia su thu muc dc chon la sdcard:
				
				//
				//mListFile.setAdapter(new ArrayAdapter<FileInfo>(this,android.R.layout.simple_list_item_single_choice, mFileAdapter.getFileInfos()));
				
			}
		});
	}


	private class DoBackgroundImportFile extends AsyncTask<String, int[], Long>{
		long totalSize = 1;
		long currentPos = 0;
		int numOfQuestionSuccess = 0;
		private class RssHandler extends DefaultHandler{
			@Override
			public void endDocument() throws SAXException {
				// TODO Auto-generated method stub
				super.endDocument();
			}
			@Override
			public void startDocument() throws SAXException {
				// TODO Auto-generated method stub
				super.startDocument();
				builder = new StringBuilder();
			}
			int isAnswerTrue;
			boolean isQuestionValid = false;
			private String currentQuestion;
			private List<Question> messages;
			private StringBuilder builder;
			private static final String questionTag = "Question";
			private static final String answerTag = "Answer";
			private static final String attIsAnswerTrue = "isTrue";
			@Override
			public void characters(char[] ch, int start, int length)
					throws SAXException {
				super.characters(ch, start, length);
				builder.append(ch, start, length);
				currentPos += ch.length;
			}
			
			@Override
			public void endElement(String uri, String localName, String name)
					throws SAXException {
				super.endElement(uri, localName, name);
					if(localName == questionTag)
					{
					//case questionTag:
						//in
						numOfQuestionSuccess++;
						publishProgress(new int[]{(int)((currentPos*100)/totalSize),numOfQuestionSuccess});
						//break;
					}else if(localName == answerTag)
					{
						if(isQuestionValid)
						{
							String strAnswer = builder.toString().trim();
							questiondata.InsertAnswer(strAnswer, isAnswerTrue);	
						}
					}
					
					builder.setLength(0);	
				}
			@Override
			public void startElement(String uri, String localName, String qName,
					Attributes attributes) throws SAXException {
				// TODO Auto-generated method stub
				super.startElement(uri, localName, qName, attributes);
				if (localName == questionTag) {
					String strQuestion = attributes.getValue("text");
					if (strQuestion == null || strQuestion.trim() == "") {
						isQuestionValid = false;
					} else {
						isQuestionValid = true;
					}
					strQuestion = strQuestion.replaceAll("[']", "''");
					questiondata.InsertQuestion(strQuestion);
					System.out.println("insert Q");
					questiondata.returnIdQuestion(strQuestion);
					System.out.println("return Q");
					// them 1 flag biet question hien tai co hop le hay ko
				} else if (localName == answerTag) {
					//
					String strIsTrue = attributes.getValue(attIsAnswerTrue);

					try {
						isAnswerTrue = Integer.parseInt(strIsTrue);
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						Log.e("KitVS", "file xml input isn't correct");
						Toast.makeText(ImportQuestion.this,
								"file xml input isn't correct",
								Toast.LENGTH_SHORT);
					}

				}
			
			}

		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			//showDialog(DIALOG_IMPORT_PROGRESS);
			isImporting = true;
			mProgressbarImportFile.setProgress(0);
			mTVStatus.setText("Importing...");
		}

		@Override
		protected void onPostExecute(Long result) {
			// TODO Auto-generated method stub
			//super.onPostExecute(result);
			Log.d("Import file","finished import");
			mProgressbarImportFile.setProgress(100);
			mProgressbarImportFile.setVisibility(View.GONE);
			mTVStatus.setVisibility(View.INVISIBLE);
			//mProgressDialog.setProgress(100);
			//removeDialog(DIALOG_IMPORT_PROGRESS);
			//dismissDialog(DIALOG_IMPORT_PROGRESS);
			Toast.makeText(getBaseContext(), "finished Import", Toast.LENGTH_SHORT).show();
//			Intent intent = new Intent(ImportFileCSV.this, vfaMain.class);
//			startActivity(intent);
			//ImportFileCSV.this.finish();
		}

		@Override
		protected void onProgressUpdate(int[]... values) {
			// TODO Auto-generated method stub
			isImporting = false;
			Log.d("ANDRp_ASYN",""+values[0]);
			//mProgressDialog.setProgress(values[0]);
			mProgressbarImportFile.setProgress(values[0][0]);
			mTVStatus.setText("Imported "+ values[0][1] + " words" + "("+((values[0][0] <100) ? values[0][0]:100)+"%)");
		}

		@Override
		protected Long doInBackground(String... params) {
			// TODO Auto-generated method stub
			try {
				readFile(params[0], "English");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		private void readFile(String filepath, String language) throws IOException {
			Log.e("cannc", language);
			try {
				File file = new File(filepath);
				FileInputStream fileIS = new FileInputStream(file);
				totalSize = fileIS.getChannel().size();
				currentPos = 0;
				numOfQuestionSuccess = 0;
				SAXParserFactory factory = SAXParserFactory.newInstance();
				try {
					SAXParser parser = factory.newSAXParser();
					RssHandler handler = new RssHandler();
					parser.parse(fileIS, handler);

				} catch (Exception e) {
					throw new RuntimeException(e);
				} 
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		


	}
	

}

